﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace IRongs.Wbt.Common.Auth
{

    public enum Method { GET, POST, PUT, DELETE };

    /// <summary>
    /// Provides an internal structure to store the query parameter
    /// </summary>
    [Serializable]
    public class QueryParameter
    {
        private string name = null;
        private string value = null;

        public QueryParameter(string name, string value)
        {
            this.name = name;
            this.value = value;
        }

        /// <summary>
        /// Gets the query parameter name.
        /// </summary>
        public string Name
        {
            get { return name; }
        }

        /// <summary>
        /// Gets the query parameter value.
        /// </summary>
        public string Value
        {
            get { return value; }
        }
    }

    /// <summary>
    /// Comparer class used to perform the sorting of the query parameters
    /// </summary>
    public class QueryParameterComparer : IComparer<QueryParameter>
    {
        #region IComparer<QueryParameter> Members

        public int Compare(QueryParameter x, QueryParameter y)
        {
            if (x.Name == y.Name)
            {
                return string.Compare(x.Value, y.Value);
            }
            else
            {
                return string.Compare(x.Name, y.Name);
            }
        }

        #endregion
    }

    public static class WebRequestHelper
    {
        public static string WebRequest(string url, string postData, Method method)
        {
            HttpWebRequest webRequest = null;
            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;

            return WebRequest(webRequest, postData, method);
        }

        public static string WebRequest(HttpWebRequest webRequest, string postData, Method method)
        {
            string responseData = "";

            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;

            if (method == Method.POST)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";
                using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(postData);
                }
            }


            using (Stream stream = webRequest.GetResponse().GetResponseStream())
            {
                using (StreamReader responseReader = new StreamReader(stream))
                {
                    responseData = responseReader.ReadToEnd();
                }
            }

            return responseData;
        }
    }

}
